package udes.assassin.structure;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.util.Log;

import udes.assassin.server.api.DataStructure.InGameUserStructure;
import udes.assassin.server.api.DataStructure.LobbyInfo;
import udes.assassin.server.api.DataStructure.UserStructure;


public class Game {
	private String mName;
	private String mOwnerName;
	public String mWinnerName;
	private List<Player> mPlayers;
	private static final int MAX_PLAYERS_IN_GAME = 8;
	
	public Game(LobbyInfo aLobbyInfo){
		mName = aLobbyInfo.roomName;
		mOwnerName = aLobbyInfo.roomOwnerName;
		  
		mPlayers = new ArrayList<Player>();
		
		for (UserStructure user : aLobbyInfo.users) {
			mPlayers.add(new Player(user));
		}
	
		Collections.sort(mPlayers);
	}
	
	public String getName(){
		return mName;
	}
	
	public String getOwnerName(){
		return mOwnerName;
	}
	
	public String getFormatedName(){
		return mOwnerName + "'s game";
	}
	
	public List<Player> getPlayers(){
		return mPlayers;
	}
	
	public Player getPlayer(String mId){
		mId = mId.trim();
		
		for (int i = 0 ; i < mPlayers.size() ; ++i) {
			if(mPlayers.get(i).getId().equals(mId)){
				Log.d("Game", mPlayers.get(i).getId());
				return mPlayers.get(i);
			}
		}
		return null;
	}
	
	public void updatePlayerInfo(List<InGameUserStructure> aUsers){
		mPlayers.clear();
		
		for (InGameUserStructure user : aUsers) {
			mPlayers.add(new Player(user));
		}
	
		Collections.sort(mPlayers);
	}
	
	public void addPlayers(Player aPlayer){
		mPlayers.add(aPlayer);
	
		Collections.sort(mPlayers);
	}
	
	public void remove(Player aPlayer){
		for (int i = 0 ; i < mPlayers.size() ; ++i) {
			if(mPlayers.get(i).getId() == aPlayer.getId()){
				mPlayers.remove(i);
				break;
			}
		}
	
		Collections.sort(mPlayers);
	}
	
	public int getNbOfPlayerInGame(){
		return mPlayers.size();
	}
	
	public String getFormatedNbOfPlayerInGame(){
		StringBuilder builder = new StringBuilder();
		builder.append(mPlayers.size());
		builder.append("/");
		builder.append(MAX_PLAYERS_IN_GAME);
		return builder.toString();
	}
	
	public boolean isAllPlayerReady(){
		for (int i = 0 ; i < mPlayers.size() ; ++i){
			if(!mPlayers.get(i).isReady()){
				return false;
			}
		}
		return true;
	}
}
